package org.gzc.queue;

/**
 * @Description: 循环队列
 * @Author: guozongchao
 * @Date: 2020/8/2 0:09
 */
public class CircleArrayQueue {
    private int capacity;
    private int[] items;
    private int front;  //指向队列头元素的上一个位置
    private int rear;  //指向队列尾元素的下标

    public CircleArrayQueue(int capacity) {
        this.capacity = capacity+1;
        this.front=0;
        this.rear=0;
        this.items = new int[this.capacity];
    }
    //判断队列是否为空
    private boolean isEmpty() {
        return front == rear;
    }

    //判断队列是否满了
    private boolean isFull() {
        return (rear+1)%capacity == front;
    }

    //入队
    public void add(int item) {
        if (isFull()) {
            throw new RuntimeException("队列已满，不能添加数据！");
        }
        items[rear]=item;
        rear=(rear+1)%capacity;
    }

    //出队
    public int get(){
        if (isEmpty()) {
            throw new RuntimeException("队列为没有数据！");
        }
        int item = items[front];
        front=(front+1)%capacity;
        return item;
    }

    //获取队列头部元素，但不出队
    public int getHeadItem() {
        return items[front];
    }

    //显示队列的数据
    public void show() {
        if (isEmpty()) {
            System.out.println("队列为没有数据！");
            return;
        }
        for (int i = front; i <front+size(); i++) {
            System.out.printf("第%d个元素为%d\n", i%capacity, items[i%capacity]);
        }
    }

    //获取队列元素个数
    public int size() {
        return (rear - front + capacity) % capacity;
    }

}
